import * as Cesium from 'cesium';
import gsap from 'gsap';

let typeNum = 0;
export default class PolylineTrailMaterialProperty {
  constructor(color = new Cesium.Color(0.7, 0.6, 1.0, 1.0)) {
    this.color = color;
    typeNum++;
    this.num = typeNum;
    this.definitionChanged = new Cesium.Event();
    Cesium.Material._materialCache.addMaterial(
      'PolylineTrailMaterial' + this.num,
      {
        fabric: {
          type: 'PolylineTrailMaterial' + typeNum,
          uniforms: {
            uTime: 0,
            image: Cesium.Material.DefaultImageId,
            color: this.color,
          },
          source: `
          // 声明全局的纹理采样器
          uniform sampler2D image; 
          czm_material czm_getMaterial(czm_materialInput materialInput) {
            // 获取默认材质
            czm_material material = czm_getDefaultMaterial(materialInput);
            // 采样纹理颜色
            // 直接使用 materialInput.st 计算颜色
            vec4 st = vec4(materialInput.st, 0.0, 1.0);

            //获取当前帧数 10秒内从0-1的变化
            float time = fract(czm_frameNumber / (60.0 * 10.0));

            time = time * (1.0 + 0.1);

            //平滑过渡效果函数 smoothstep(edge0,dege1,value)
            float alpha = smoothstep(time-0.1, time, st.s) * step(-time,-st.s);
           


            // 根据时间动态调整透明度，使其具有闪烁效果
            //float alpha = abs(sin(uTime * 5.0)); 

            // 应用纹理颜色和动态透明度
             material.alpha = alpha;
            
             material.diffuse = color.rgb; 

            return material;
          }
        `,
        },
      }
    );

    this.params = {
      uTime: 0,
      image: Cesium.Material.DefaultImageId,
    };
    gsap.to(this.params, {
      uTime: 1,
      duration: 2,
      repeat: -1,
      yoyo: true,
    });
  }
  getType() {
    // 返回材质类型
    return 'PolylineTrailMaterial' + this.num;
  }
  getValue(time, result) {
    result.uTime = this.params.uTime;
    result.image = this.params.image; // 传递 image 这个 uniform
    return result;
  }
  equals(other) {
    // 判断两个材质是否相等
    return (
      other instanceof PolylineTrailMaterialProperty &&
      this.color === other.color
    );
  }
}
